import config
import time
from document import Document
from utils import *

def register():
	return Note()

class Note:
	def __init__(self):
		self.type = 'passive'
		self.help = \
'''个人笔记：
	用法：
		*笔记 添加
		(笔记内容)
		*笔记 总数
		*笔记 列表
		*笔记 查询 (编号)
		*笔记 搜索
		(笔记内容)
		*笔记 删除 (编号)
		*笔记 更改 (编号)
		(笔记内容)
		*笔记 追加 (编号)
		(笔记内容)
	只接受文本内容，各QQ号间独立，不担保数据安全，仅供方便使用，不建议滥用。'''

	def makeNote(self, text, **kwargs):
		return {'text': text, **kwargs}

	def makeMsg(self, note):
		chain = MsgChain()
		if 'time' in note:
			chain.addPlain('笔记时间：' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(note['time'])) + '\n')
		chain.addPlain(note['text'] + '\n')
		return chain

	def run(self, gum, msg):
		if not msg['type'] in ['FriendMessage', 'GroupMessage'] \
				or len(msg['messageChain']) <= 1 \
				or msg['messageChain'][1]['type'] != 'Plain' \
				or msg['messageChain'][1]['text'].split()[0] != '*笔记' \
				or len(msg['messageChain'][1]['text'].split()) <= 1:
			return

		with trying():
			target = msg['sender']['id']
			lines = msg['messageChain'][1]['text'].split('\n')
			splitted = lines[0].split()

			doc = Document(config.bubbles.note.filename % target)
			if not doc.notes:
				doc.notes = []

			if splitted[1] == '添加':
				note = self.makeNote('\n'.join(lines[1:]), time=time.time())
				doc.notes.append(note)
				autoReply(f'添加成功，编号为{len(doc.notes)}', gum)
			elif splitted[1] == '总数':
				autoReply(f'有{len(doc.notes)}条笔记哦', gum)
			elif splitted[1] == '列表':
				if not doc.notes:
					autoReply('现在还没有笔记哦', gum)
				i = 1
				for note in doc.notes:
					chain = MsgChain(t=f'笔记{i}：\n')
					chain.append(self.makeMsg(note))
					autoReply(chain, gum)
					time.sleep(config.bubbles.note.sleepingSeconds)
					i += 1
			elif splitted[1] == '查询':
				i = int(splitted[2])
				if i - 1 < 0 or i - 1 >= len(doc.notes):
					autoReply('没有这条笔记', gum)
				else:
					autoReply(self.makeMsg(doc.notes[i - 1]), gum)
			elif splitted[1] == '搜索':
				joined = '\n'.join(lines[1:])
				i = 0
				flag = False
				for note in doc.notes:
					i += 1
					if not joined in note['text']:
						continue
					flag = True
					chain = MsgChain(t=f'笔记{i}：\n')
					chain.append(self.makeMsg(note))
					autoReply(chain, gum)
					time.sleep(config.bubbles.note.sleepingSeconds)
				if not flag:
					autoReply('没有相关的笔记', gum)
			elif splitted[1] == '删除':
				doc.notes.pop(int(splitted[2]) - 1)
				autoReply('删除成功', gum)
			elif splitted[1] == '更改':
				note = self.makeNote('\n'.join(lines[1:]), time=time.time())
				doc.notes[int(splitted[2]) - 1] = note
				autoReply('更改成功', gum)
			elif splitted[1] == '追加':
				i = int(splitted[2])
				if i - 1 < 0 or i - 1 >= len(doc.notes):
					autoReply('没有这条笔记', gum)
				else:
					note = self.makeNote(doc.notes[i - 1]['text'] + '\n' + '\n'.join(lines[1:]), time=time.time())
					doc.notes[int(splitted[2]) - 1] = note
					autoReply('更改成功', gum)

			doc.store()